package org.example.service;

import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.CloseStatus;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import okhttp3.*;
import java.util.concurrent.TimeUnit;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URI;
import java.util.concurrent.CompletableFuture;

import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import org.springframework.web.socket.client.WebSocketClient;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketHandler;

/**
 * TTS桥接服务，用于解决VoiceWebSocketHandler和OlamaService之间的循环依赖
 * 这个服务负责处理TTS相关的功能，作为两个组件之间的中介
 */
@Service
public class TTSBridgeService {
    private static final Logger logger = LoggerFactory.getLogger(TTSBridgeService.class);

    private final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<>();
    // 添加TTS WebSocket连接缓存
    private final Map<String, WebSocketSession> ttsSessions = new ConcurrentHashMap<>();
    // 添加连接过期时间
    private final Map<String, Long> ttsSessionExpiry = new ConcurrentHashMap<>();
    // 连接过期时间（毫秒）
    private static final long TTS_SESSION_EXPIRY_TIME = 120000; // 延长到120秒
    // 心跳检查间隔（毫秒）
    private static final long HEARTBEAT_CHECK_INTERVAL = 15000; // 15秒检查一次

    private final OkHttpClient httpClient;
    private final WebSocketClient webSocketClient;

    @Value("${cosyvoice.api.url:http://localhost:8001}")
    private String cosyVoiceApiUrl;

    @Value("${cosyvoice.ws.url:ws://localhost:8001/ws/tts}")
    private String cosyVoiceWsUrl;

    private VoiceService voiceService;

    @Autowired
    public TTSBridgeService(VoiceService voiceService) {
        this.voiceService = voiceService;

        // 配置OkHttpClient，设置适当的超时
        this.httpClient = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS) // 增加连接超时
                .readTimeout(60, TimeUnit.SECONDS) // 增加读取超时
                .writeTimeout(60, TimeUnit.SECONDS) // 增加写入超时
                .pingInterval(30, TimeUnit.SECONDS) // 添加ping间隔
                .build();

        // 初始化WebSocket客户端
        this.webSocketClient = new StandardWebSocketClient();

        // 启动定期清理和心跳检查线程
        startMaintenanceThread();

        logger.info("TTSBridgeService初始化完成，CosyVoice API地址: {}, WebSocket地址: {}", cosyVoiceApiUrl, cosyVoiceWsUrl);
    }

    // 启动定期清理和心跳检查线程
    private void startMaintenanceThread() {
        Thread maintenanceThread = new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(HEARTBEAT_CHECK_INTERVAL);

                    // 检查已有的WebSocket连接
                    checkWebSocketConnections();

                    // 清理过期的会话
                    cleanupExpiredSessions();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    break;
                }
            }
        });
        maintenanceThread.setDaemon(true);
        maintenanceThread.setName("TTS-WebSocket-Maintenance");
        maintenanceThread.start();
        logger.info("WebSocket维护线程已启动，检查间隔: {}ms", HEARTBEAT_CHECK_INTERVAL);
    }

    // 检查WebSocket连接状态，并发送心跳响应
    private void checkWebSocketConnections() {
        logger.debug("开始检查WebSocket连接状态，当前连接数: {}", ttsSessions.size());

        for (Map.Entry<String, WebSocketSession> entry : ttsSessions.entrySet()) {
            String sessionId = entry.getKey();
            WebSocketSession session = entry.getValue();

            try {
                if (session != null && session.isOpen()) {
                    // 更新会话过期时间
                    ttsSessionExpiry.put(sessionId, System.currentTimeMillis() + TTS_SESSION_EXPIRY_TIME);
                    logger.debug("WebSocket会话 {} 仍然有效", sessionId);
                } else {
                    // 移除无效会话
                    ttsSessions.remove(sessionId);
                    ttsSessionExpiry.remove(sessionId);
                    logger.info("已移除无效的WebSocket会话: {}", sessionId);
                }
            } catch (Exception e) {
                logger.error("检查WebSocket会话 {} 状态时出错: {}", sessionId, e.getMessage());
            }
        }
    }

    // 清理过期的TTS会话
    private void cleanupExpiredSessions() {
        long now = System.currentTimeMillis();
        ttsSessionExpiry.forEach((sessionId, expiryTime) -> {
            if (now > expiryTime) {
                WebSocketSession session = ttsSessions.remove(sessionId);
                if (session != null && session.isOpen()) {
                    try {
                        session.close();
                    } catch (IOException e) {
                        logger.error("关闭过期TTS会话时出错: {}", e.getMessage());
                    }
                }
                ttsSessionExpiry.remove(sessionId);
                logger.info("已清理过期的TTS会话: {}", sessionId);
            }
        });
    }

    // 获取或创建TTS WebSocket会话 - 优化版本
    private WebSocketSession getOrCreateTTSSession(String sessionId) throws Exception {
        WebSocketSession session = ttsSessions.get(sessionId);

        // 检查现有会话是否有效
        if (session != null) {
            if (session.isOpen()) {
                // 更新过期时间
                ttsSessionExpiry.put(sessionId, System.currentTimeMillis() + TTS_SESSION_EXPIRY_TIME);
                logger.info("复用现有TTS WebSocket会话: {}", sessionId);
                return session;
            } else {
                // 移除无效会话
                ttsSessions.remove(sessionId);
                ttsSessionExpiry.remove(sessionId);
                logger.info("移除无效的TTS WebSocket会话: {}", sessionId);
            }
        }

        logger.info("创建新的TTS WebSocket会话: {}", sessionId);
        // 创建新的WebSocket会话
        CompletableFuture<WebSocketSession> sessionFuture = new CompletableFuture<>();
        WebSocketHandler handler = new TextWebSocketHandler() {
            @Override
            public void afterConnectionEstablished(WebSocketSession session) {
                logger.info("TTS WebSocket连接已建立: {}", sessionId);
                sessionFuture.complete(session);
            }

            @Override
            public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) {
                try {
                    if (message instanceof TextMessage) {
                        String payload = ((TextMessage) message).getPayload();
                        logger.info("收到TTS WebSocket文本消息: {}", payload);

                        // 处理心跳消息
                        if (payload.contains("\"type\":\"heartbeat\"")) {
                            // 发送心跳响应
                            JsonObject heartbeatResponse = new JsonObject();
                            heartbeatResponse.addProperty("type", "heartbeat_response");
                            heartbeatResponse.addProperty("timestamp", System.currentTimeMillis());
                            session.sendMessage(new TextMessage(heartbeatResponse.toString()));
                            logger.debug("已发送心跳响应");

                            // 更新过期时间
                            ttsSessionExpiry.put(sessionId, System.currentTimeMillis() + TTS_SESSION_EXPIRY_TIME);
                            return;
                        }

                        // 获取前端会话并转发消息
                        WebSocketSession frontendSession = sessions.get(sessionId);
                        if (frontendSession != null && frontendSession.isOpen()) {
                            JsonObject response = new JsonObject();
                            response.addProperty("type", "tts_progress");
                            response.addProperty("data", payload);
                            frontendSession.sendMessage(new TextMessage(response.toString()));
                            logger.info("已成功转发文本消息到前端");
                        } else {
                            logger.error("前端会话无效，无法转发消息");
                        }
                    } else if (message instanceof BinaryMessage) {
                        BinaryMessage binaryMessage = (BinaryMessage) message;
                        byte[] data = binaryMessage.getPayload().array();
                        logger.info("收到TTS WebSocket二进制消息，大小: {} 字节", data.length);

                        // 获取前端会话并转发二进制数据
                        WebSocketSession frontendSession = sessions.get(sessionId);
                        if (frontendSession != null && frontendSession.isOpen()) {
                            frontendSession.sendMessage(new BinaryMessage(ByteBuffer.wrap(data)));
                            logger.info("已成功转发二进制数据到前端，大小: {} 字节", data.length);
                        } else {
                            logger.error("前端会话无效，无法转发二进制数据");
                        }
                    }
                } catch (Exception e) {
                    logger.error("处理WebSocket消息时出错: {}", e.getMessage(), e);
                }
            }

            @Override
            public void handleTransportError(WebSocketSession session, Throwable exception) {
                logger.error("TTS WebSocket传输错误: {}", exception.getMessage(), exception);
                sessionFuture.completeExceptionally(exception);
            }

            @Override
            public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
                logger.info("TTS WebSocket连接已关闭: {}, 状态: {}", sessionId, status);
                ttsSessions.remove(sessionId);
                ttsSessionExpiry.remove(sessionId);
            }
        };

        logger.info("正在连接到TTS WebSocket服务器: {}", cosyVoiceWsUrl);
        try {
            // 使用字符串URL创建WebSocket连接
            webSocketClient.execute(handler, cosyVoiceWsUrl);

            // 等待连接建立，设置超时
            session = sessionFuture.get(10, TimeUnit.SECONDS);

            // 验证连接是否成功建立
            if (session != null && session.isOpen()) {
                ttsSessions.put(sessionId, session);
                ttsSessionExpiry.put(sessionId, System.currentTimeMillis() + TTS_SESSION_EXPIRY_TIME);
                logger.info("TTS WebSocket会话创建成功: {}", sessionId);

                // 开始使用连接时，主动发送一条初始消息以确认连接正常
                JsonObject initMessage = new JsonObject();
                initMessage.addProperty("type", "connection_init");
                initMessage.addProperty("session_id", sessionId);
                initMessage.addProperty("timestamp", System.currentTimeMillis());
                session.sendMessage(new TextMessage(initMessage.toString()));
                logger.info("已发送连接初始化消息");

                return session;
            } else {
                logger.error("TTS WebSocket会话创建失败: 连接未打开");
                throw new Exception("TTS WebSocket会话创建失败: 连接未打开");
            }
        } catch (Exception e) {
            logger.error("创建TTS WebSocket会话时出错: {}", e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 注册WebSocketSession
     * 
     * @param sessionId 会话ID
     * @param session   WebSocket会话
     */
    public void registerSession(String sessionId, WebSocketSession session) {
        sessions.put(sessionId, session);
        logger.debug("已注册会话: {}", sessionId);
    }

    /**
     * 移除WebSocketSession
     * 
     * @param sessionId 会话ID
     */
    public void removeSession(String sessionId) {
        sessions.remove(sessionId);
        logger.debug("已移除会话: {}", sessionId);
    }

    /**
     * 处理生成的AI响应文本，调用流式TTS进行语音合成
     * 使用WebSocket API，将音频分块发送给客户端
     * 
     * @param sessionId 会话ID
     * @param text      AI生成的文本
     * @param speaker   说话人ID
     */
    public void processTTSForAIResponseStreaming(String sessionId, String text, String speaker) {
        if (text == null || text.trim().isEmpty()) {
            logger.warn("AI响应文本为空，跳过TTS处理，会话ID: {}", sessionId);
            return;
        }

        logger.info("开始WebSocket TTS处理，文本长度: {}, 说话人: {}, 会话ID: {}", text.length(), speaker, sessionId);
        WebSocketSession frontendSession = sessions.get(sessionId);
        if (frontendSession == null || !frontendSession.isOpen()) {
            logger.error("前端会话已关闭或不存在，无法为AI响应生成TTS，会话ID: {}, 总会话数: {}", sessionId, sessions.size());
            if (!sessions.isEmpty()) {
                logger.info("当前活跃的会话ID: {}", sessions.keySet());
            }
            return;
        }

        try {
            // 发送TTS元数据给客户端
            JsonObject ttsMetadata = new JsonObject();
            ttsMetadata.addProperty("type", "tts_metadata");
            ttsMetadata.addProperty("text", text);
            ttsMetadata.addProperty("ai_generated", true);
            ttsMetadata.addProperty("speaker", speaker);
            ttsMetadata.addProperty("streaming", true);
            sendMessageToFrontend(frontendSession, ttsMetadata.toString());
            logger.info("已成功向前端发送WebSocket TTS元数据 [{}]", sessionId);

            // 创建TTS请求对象
            JsonObject ttsRequest = new JsonObject();
            ttsRequest.addProperty("text", text);
            ttsRequest.addProperty("speaker_id", speaker);
            ttsRequest.addProperty("speed", 1.0);
            ttsRequest.addProperty("enable_segmentation", true);

            // 使用CompletableFuture来管理异步WebSocket连接
            CompletableFuture<Void> wsCompletionFuture = new CompletableFuture<>();

            // 获取或创建TTS WebSocket会话
            WebSocketSession ttsSession = getOrCreateTTSSession(sessionId);

            // 发送TTS请求
            ttsSession.sendMessage(new TextMessage(ttsRequest.toString()));
            logger.info("已发送TTS请求: {}", ttsRequest.toString());

            // 创建WebSocket处理器
            WebSocketHandler wsHandler = new TextWebSocketHandler() {
                boolean wavHeaderSent = false;
                int totalBytesReceived = 0;
                int messageCount = 0;

                @Override
                public void handleMessage(WebSocketSession ttsSession, WebSocketMessage<?> message) throws Exception {
                    try {
                        messageCount++;
                        if (message instanceof TextMessage) {
                            // 处理文本消息（控制信息）
                            String payload = ((TextMessage) message).getPayload();
                            logger.info("收到TTS服务器文本消息 [{}]: {}", sessionId, payload);

                            // 获取前端WebSocket会话
                            WebSocketSession frontendSession = sessions.get(sessionId);

                            // 检查会话是否有效
                            if (frontendSession != null && frontendSession.isOpen()) {
                                JsonObject response = new JsonObject();
                                response.addProperty("type", "tts_progress");
                                response.addProperty("data", payload);
                                sendMessageToFrontend(frontendSession, response.toString());
                                logger.info("已成功向前端WebSocket转发TTS服务器文本消息 [{}]", sessionId);

                                // 检查是否是完成消息
                                if (payload.contains("\"type\":\"complete\"")) {
                                    logger.info("TTS处理完成，共接收 {} 条消息，总字节数: {}", messageCount, totalBytesReceived);

                                    // 发送TTS完成通知
                                    JsonObject ttsCompleteMsg = new JsonObject();
                                    ttsCompleteMsg.addProperty("type", "tts_complete");
                                    ttsCompleteMsg.addProperty("session_id", sessionId);
                                    ttsCompleteMsg.addProperty("total_bytes", totalBytesReceived);
                                    ttsCompleteMsg.addProperty("total_messages", messageCount);
                                    sendMessageToFrontend(frontendSession, ttsCompleteMsg.toString());
                                    logger.info("已成功向前端WebSocket发送TTS完成通知 [{}]", sessionId);

                                    // 不关闭WebSocket连接，而是更新过期时间
                                    ttsSessionExpiry.put(sessionId,
                                            System.currentTimeMillis() + TTS_SESSION_EXPIRY_TIME);
                                    wsCompletionFuture.complete(null);
                                }

                                // 检查是否是错误消息
                                if (payload.contains("\"type\":\"error\"")) {
                                    logger.error("TTS处理出错 [{}]: {}", sessionId, payload);

                                    // 创建并发送错误消息
                                    JsonObject errorMsg = new JsonObject();
                                    errorMsg.addProperty("type", "tts_error");
                                    errorMsg.addProperty("message", "语音合成出错");
                                    errorMsg.addProperty("session_id", sessionId);
                                    errorMsg.addProperty("details", payload);
                                    sendMessageToFrontend(frontendSession, errorMsg.toString());
                                    logger.info("已成功向前端WebSocket发送TTS错误通知 [{}]", sessionId);

                                    // 不关闭WebSocket连接，而是更新过期时间
                                    ttsSessionExpiry.put(sessionId,
                                            System.currentTimeMillis() + TTS_SESSION_EXPIRY_TIME);
                                    wsCompletionFuture.complete(null);
                                }
                            } else {
                                logger.error("前端WebSocket会话无效或已关闭 [{}], 无法转发文本消息", sessionId);
                            }
                        } else if (message instanceof BinaryMessage) {
                            // 处理二进制消息（音频数据）
                            BinaryMessage binaryMessage = (BinaryMessage) message;
                            byte[] audioData = binaryMessage.getPayload().array();
                            totalBytesReceived += audioData.length;

                            logger.info("收到TTS服务器二进制消息 [{}], 大小: {} 字节, 累计: {} 字节",
                                    sessionId, audioData.length, totalBytesReceived);

                            // 将音频数据转发给前端客户端WebSocket
                            try {
                                // 获取前端WebSocket会话
                                WebSocketSession frontendSession = sessions.get(sessionId);

                                // 检查前端会话是否有效
                                if (frontendSession == null || !frontendSession.isOpen()) {
                                    logger.error("前端WebSocket会话无效或已关闭 [{}], 无法转发音频数据", sessionId);
                                    return;
                                }

                                // 发送音频数据到前端
                                ByteBuffer audioBuffer = ByteBuffer.wrap(audioData);
                                frontendSession.sendMessage(new BinaryMessage(audioBuffer));
                                logger.info("已成功向前端WebSocket发送音频数据 [{}], 大小: {} 字节", sessionId, audioData.length);

                                // 每5个音频包发送一次进度更新消息
                                if (messageCount % 5 == 0) {
                                    JsonObject progressMsg = new JsonObject();
                                    progressMsg.addProperty("type", "tts_progress");
                                    progressMsg.addProperty("bytes_received", totalBytesReceived);
                                    progressMsg.addProperty("message_count", messageCount);
                                    sendMessageToFrontend(frontendSession, progressMsg.toString());
                                    logger.info("已发送TTS进度更新消息到前端 [{}], 已处理消息数: {}", sessionId, messageCount);
                                }
                            } catch (Exception e) {
                                logger.error("向前端转发音频数据失败 [{}]: {}", sessionId, e.getMessage(), e);
                            }
                        }
                    } catch (Exception e) {
                        logger.error("处理WebSocket消息时出错 [{}]: {}", sessionId, e.getMessage(), e);
                        sendTTSError(frontendSession, sessionId, "处理音频数据时出错: " + e.getMessage());
                        wsCompletionFuture.completeExceptionally(e);
                    }
                }

                @Override
                public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
                    logger.error("WebSocket传输错误 [{}]: {}", sessionId, exception.getMessage(), exception);
                    sendTTSError(frontendSession, sessionId, "WebSocket传输错误: " + exception.getMessage());
                    wsCompletionFuture.completeExceptionally(exception);
                }

                @Override
                public void afterConnectionClosed(WebSocketSession session,
                        org.springframework.web.socket.CloseStatus status) throws Exception {
                    logger.info("WebSocket连接已关闭 [{}], 状态: {}, 共接收 {} 条消息，总字节数: {}",
                            sessionId, status, messageCount, totalBytesReceived);
                    // 如果还未完成，则完成future
                    if (!wsCompletionFuture.isDone()) {
                        wsCompletionFuture.complete(null);
                    }
                }
            };

            // 等待连接处理完成
            wsCompletionFuture.get(60, TimeUnit.SECONDS);
            logger.info("WebSocket TTS处理完成，会话ID: {}", sessionId);
        } catch (Exception e) {
            logger.error("为AI响应生成WebSocket TTS时出错: {}", e.getMessage(), e);
            try {
                sendTTSError(frontendSession, sessionId, "语音合成出错: " + e.getMessage());
            } catch (Exception ex) {
                logger.error("发送错误消息失败", ex);
            }
        }
    }

    /**
     * 发送TTS错误消息
     * 
     * @param session      WebSocket会话
     * @param sessionId    会话ID
     * @param errorMessage 错误消息
     */
    private void sendTTSError(WebSocketSession session, String sessionId, String errorMessage) {
        try {
            JsonObject errorMsg = new JsonObject();
            errorMsg.addProperty("type", "tts_error");
            errorMsg.addProperty("message", errorMessage);
            errorMsg.addProperty("session_id", sessionId);
            sendMessage(session, errorMsg.toString());
        } catch (Exception e) {
            logger.error("发送TTS错误消息失败", e);
        }
    }

    /**
     * 处理生成的AI响应文本，根据配置选择流式或非流式TTS
     * 
     * @param sessionId 会话ID
     * @param text      AI生成的文本
     * @param speaker   说话人ID
     */
    public void processTTSForAIResponse(String sessionId, String text, String speaker) {
        // 使用WebSocket TTS API
        processTTSForAIResponseStreaming(sessionId, text, speaker);
    }

    /**
     * 发送文本消息到WebSocket客户端
     * 
     * @param session WebSocket会话
     * @param message 消息内容
     */
    private void sendMessage(WebSocketSession session, String message) {
        try {
            if (session.isOpen()) {
                session.sendMessage(new TextMessage(message));
            }
        } catch (IOException e) {
            logger.error("发送WebSocket消息时出错", e);
        }
    }

    /**
     * 专用方法：向前端WebSocket客户端发送消息，带详细日志
     */
    private void sendMessageToFrontend(WebSocketSession session, String message) {
        try {
            if (session != null && session.isOpen()) {
                session.sendMessage(new TextMessage(message));
                logger.info("前端WebSocket消息发送成功，消息类型: {}",
                        message.contains("type")
                                ? message.substring(message.indexOf("type"), message.indexOf("type") + 20)
                                : "未知");
            } else {
                logger.error("无法发送前端WebSocket消息: 会话为null或已关闭");
            }
        } catch (IOException e) {
            logger.error("向前端发送WebSocket消息失败: {}", e.getMessage(), e);
        }
    }

    /**
     * 向前端发送二进制音频数据，带详细日志
     */
    private void sendBinaryToFrontend(WebSocketSession session, byte[] data, String sessionId) {
        try {
            if (session != null && session.isOpen()) {
                ByteBuffer buffer = ByteBuffer.wrap(data);
                session.sendMessage(new BinaryMessage(buffer));
                logger.info("向前端WebSocket成功发送二进制数据 [{}], 大小: {} 字节", sessionId, data.length);
            } else {
                logger.error("无法发送前端WebSocket二进制数据 [{}]: 会话为null或已关闭", sessionId);
            }
        } catch (IOException e) {
            logger.error("向前端发送WebSocket二进制数据失败 [{}]: {}", sessionId, e.getMessage(), e);
        }
    }

    /**
     * 更新AI处理状态
     *
     * @param sessionId    会话ID
     * @param isProcessing 是否正在处理
     */
    public void updateAiProcessingStatus(String sessionId, boolean isProcessing) {
        WebSocketSession session = sessions.get(sessionId);
        if (session == null || !session.isOpen()) {
            logger.warn("无法更新AI处理状态，会话 {} 不存在或已关闭", sessionId);
            return;
        }

        try {
            // 发送状态更新消息
            JsonObject statusMsg = new JsonObject();
            statusMsg.addProperty("type", "ai_status");
            statusMsg.addProperty("status", isProcessing ? "processing" : "completed");
            statusMsg.addProperty("session_id", sessionId);
            session.sendMessage(new TextMessage(statusMsg.toString()));

            logger.info("已更新AI处理状态: {}, 会话ID: {}", isProcessing ? "处理中" : "已完成", sessionId);

            // 如果处理完成，确保前端知道
            if (!isProcessing) {
                JsonObject processingMsg = new JsonObject();
                processingMsg.addProperty("type", "ai_processing");
                processingMsg.addProperty("status", "completed");
                session.sendMessage(new TextMessage(processingMsg.toString()));
            }
        } catch (Exception e) {
            logger.error("更新AI处理状态失败", e);
        }
    }

    public void handleTTSRequest(String sessionId, String text, String voiceId, String modelId) {
        logger.info("处理TTS请求 - 会话ID: {}, 文本长度: {}, 声音ID: {}, 模型ID: {}",
                sessionId, text.length(), voiceId, modelId);

        try {
            // 获取或创建TTS WebSocket会话
            WebSocketSession ttsSession = getOrCreateTTSSession(sessionId);
            if (ttsSession == null || !ttsSession.isOpen()) {
                logger.error("无法创建或获取TTS WebSocket会话");
                return;
            }

            // 构建TTS请求
            JsonObject ttsRequest = new JsonObject();
            ttsRequest.addProperty("text", text);
            ttsRequest.addProperty("voice_id", voiceId);
            ttsRequest.addProperty("model_id", modelId);
            ttsRequest.addProperty("session_id", sessionId);

            // 发送TTS请求
            ttsSession.sendMessage(new TextMessage(ttsRequest.toString()));
            logger.info("已发送TTS请求到WebSocket服务器");

            // 发送元数据到前端
            WebSocketSession frontendSession = sessions.get(sessionId);
            if (frontendSession != null && frontendSession.isOpen()) {
                JsonObject metadata = new JsonObject();
                metadata.addProperty("type", "tts_start");
                metadata.addProperty("session_id", sessionId);
                metadata.addProperty("text_length", text.length());
                frontendSession.sendMessage(new TextMessage(metadata.toString()));
                logger.info("已发送TTS元数据到前端");
            } else {
                logger.error("前端会话无效，无法发送元数据");
            }

        } catch (Exception e) {
            logger.error("处理TTS请求时出错: {}", e.getMessage(), e);
            // 尝试发送错误消息到前端
            try {
                WebSocketSession frontendSession = sessions.get(sessionId);
                if (frontendSession != null && frontendSession.isOpen()) {
                    JsonObject errorResponse = new JsonObject();
                    errorResponse.addProperty("type", "tts_error");
                    errorResponse.addProperty("message", "处理TTS请求时出错: " + e.getMessage());
                    frontendSession.sendMessage(new TextMessage(errorResponse.toString()));
                    logger.info("已发送错误消息到前端");
                }
            } catch (Exception ex) {
                logger.error("发送错误消息到前端时出错: {}", ex.getMessage(), ex);
            }
        }
    }
}